package com.bitin.adorn.core.security.exception;

import com.bitin.adorn.common.payload.ApiResultCode;
import com.bitin.adorn.common.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 认证异常处理
 *
 * @author Mr.Lu
 * @since 2024/12/24 17:10
 */
@Component
public class Auth2AuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        int status = response.getStatus();
        if (status == HttpServletResponse.SC_NOT_FOUND) {
            // 资源不存在
            ResponseUtils.writeErrorMessage(response, ApiResultCode.USER_RESOURCE_NOT_FOUND);
        } else {

            if (exception instanceof BadCredentialsException) {
                // 用户名或密码错误
                ResponseUtils.writeErrorMessage(response, ApiResultCode.USER_PASSWORD_ERROR);
            } else {
                // 未认证或者token过期
                ResponseUtils.writeErrorMessage(response, ApiResultCode.ACCESS_TOKEN_INVALID);
            }
        }
    }
}
